<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: UserGroupRole.php 262 2011-07-23 15:51:14Z beimuaihui $
 */


Zend_Loader::loadClass("Baogg_Db_Table");

//class UserGroupRole extends Baogg_Db_Table {
class UserGroupRole  extends Baogg_Db_Table {
	/**
	 * The default table name 
	 */
	protected $_name;
	protected $_db ;
	protected $_primary; 
	
	function __construct() {
		$this->_name =   'user_group_role';		
		$this->primary= $this->_primary='user_group_role_id';
		parent::__construct();
	}
	
	

	


	function getSame($arr) {	
		$ret=array();
		
		$where['user_group_role_id']=$arr['user_group_role_id'];
		return parent::getSame($where);
	     	
	
	}
	
	function reset($user_id,$grant_user_id=0)
	{	
		$rows_affected=false;
		
		if(!$grant_user_id){
			$grant_user_id=$_SESSION['admin']['user']['user_id'];			
		}
		
		$User=new User();
		//if admin,delete all group and role ,else delete grant_user's group role . 
		if($User->isAdmin($grant_user_id)){
			$where = $this->_db->quoteInto("user_id = ?", $user_id);	
			$rows_affected = $this->_db->delete($this->_name, $where);

		}else{
			
			$where = $this->_db->quoteInto("user_id = ?", $grant_user_id);	
			$rs_grant = $this->getList(array($where));
			foreach((array)$rs_grant as $v){
				//echo '<pre>';print_r($rs_grant);exit;
				$where = $this->_db->quoteInto("user_id = ? ", (int)$user_id);
				$where.=$this->_db->quoteInto(" and user_group_id=? ",(int)$v['user_group_id']);
				$where.=$this->_db->quoteInto("  and role_id=? ",(int)$v['role_id']);

				$rows_affected = $this->_db->delete($this->_name, $where);
			}
		}

		
		return $rows_affected;
	}
	
	function getGroupIdsByUserId($user_id=0)
	{
		$ret=array();
		
		if(!$user_id){
			$user_id=$_SESSION['admin']['user']['user_id'];
		}
		$rs=$this->getList(array("user_id"=>$user_id));
		foreach((array)$rs as $v){
			$ret[]=$v['user_group_id'];			
		}
		return $ret;
	}
	
	function addDefaultRole($user_id=0,$group_id=0){
		$group_id=$group_id?$group_id:@$_SESSION['admin']['user_group_role']['user_group_id'][0];
		if($user_id && $group_id){					
			$UserGroup=new UserGroup();
			$rs_user_group=$UserGroup->getOne((int)$group_id);
			$Role=new Role();
			$rs_role=$Role->getList(array("is_default"=>1,"level_id"=>@$rs_user_group[0]['level_id']));
			if($rs_role){
				$this->_insert(array("user_id"=>$user_id,"user_group_id"=>0,"role_id"=>@$rs_role[0]['role_id']));
				return true;
			}
		}
		return false;
	}


}
